# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper

  FLASH_INFO_TYPE_TO_CLASS = {
    FlashInfo::ERROR => "flash_info_error",
    FlashInfo::NOTICE => "flash_info_notice"
  }

  def session_user
    session[:user]
  end
  
  # if flash[:info] exists returns <p> tag with FlashInfo formatted message
  # empty string otherwise
  def flash_info_tag(fi_ = nil)
    (fi = fi_ || flash_info) \
      ? content_tag("p", fi.message, :class => FLASH_INFO_TYPE_TO_CLASS[fi.type]) \
      : ""
  end

  def bool_to_int(true_)
    true_ ? 1 : 0
  end

  def flash_info
    flash[:info]
  end

  def date_format(date)
    case date.class.to_s
      when 'Date'
        Time.local(date.year, date.mon.to_s, date.mday.to_s).strftime("%m/%d/%y")
      when 'Time'
        date.strftime("%m/%d/%y %I.%M.%S%p")
      when 'Array'
        date.collect {|i| date_format(Date.parse(i))}
      else
        date        
      end
  end

  def can_add_ecase?
    session_user && session_user.can_add_ecase?
  end

  def can_edit_ecase?(ecase_)
    session_user && session_user.can_edit_ecase?(ecase_)
  end

  def can_delete_ecase?(ecase_)
    session_user && session_user.can_delete_ecase?(ecase_)
  end
  
  def can_add_event?(event_)
    session_user && session_user.can_add_event?(event_)
  end

  def can_edit_event?(event_)
    session_user && session_user.can_edit_event?(event_)
  end

  def can_delete_event?(event_)
    session_user && session_user.can_delete_event?(event_)
  end

  def can_add_resources?
    session_user && session_user.can_add_resources?
  end

  def can_edit_resources?(resource_)
    session_user && session_user.can_edit_resources?(resource_)
  end

  def can_delete_resources?(resource_)
    session_user && session_user.can_delete_resources?(resource_)
  end

  #Displays duration formatted as mins:secs
  def sound_duration(seconds)
    return '00:00' if seconds.nil?
    secs = seconds % 60
    mins = ((seconds-secs)/60)
    sprintf("%02d:%02d",mins,secs)
  end
  
  def can_add_comment?
    session_user && session_user.can_add_comment?
  end
  
  def can_edit_comment?(comment_)
    session_user && session_user.can_edit_comment?(comment_)
  end

  def h_spacer(height_)
    content_tag("div", " ", :style => "height: " + height_.to_s + "px;")
  end
  
  def text_or_link(return_text, text_, controller_, action_)
    return_text \
      ? text_ \
      : link_to(text_, :controller => controller_, :action => action_)
  end
end